<?php

namespace App\Http\Controllers\Admin\AirLine\Flight;

use App\Exceptions\AppException;
use App\Exports\EmailExport;
use App\Http\Controllers\Admin\AirLine\Base\Flight;
use App\Http\Controllers\Controller;
use App\Http\Requests\airline\flight\TransportRequest;
use App\Mail\FlightMail;
use App\Models\AgentModel;
use App\Models\airline\base\CompanyModel;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\airline\base\RouteModel;
use App\Models\base\SubjectModel;
use App\Models\DictionaryModel;
use App\Models\EmailModel;
use App\Models\FlightBanModel;
use App\Models\FlightItemModel;
use App\Models\FlightModel;
use App\Models\OrderModel;
use App\Models\OrderReceiveModel;
use App\Models\TakeOrderModel;
use App\Models\TakeOrderPayModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;

//航班运力
class Transport extends Controller
{
    use TransportRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $flight_number = $request->input('fightNumber', '');
        $route_id = $request->input('route_id', '');
        $airline_company_id = $request->input('airline_company_id', '');
        $take_off_time_start = $request->input('take_off_time_start', '');
        $take_off_time_end = $request->input('take_off_time_end', '');
        $destination_ids = $request->input('des_country', []);
        $status = $request->input('status', '');
        $take_order_sn = $request->input('take_order_sn', '');

        $query = FlightModel::query();

        if($route_id){
            $query->whereIn('id', function($query) use ($route_id){
                $query->select('flight_id')
                    ->from((new FlightItemModel())->getTable())
                    ->where('route_id', $route_id);
            });
        }

        if($destination_ids){
            $query->whereIn('arrive_port_code', $destination_ids);
        }

        if($take_order_sn){
            $query->whereIn('id', function($query) use ($take_order_sn){
                $query->select('flight_id')
                    ->from((new TakeOrderModel())->getTable())
                    ->where('sn', $take_order_sn);
            });
        }

        if($airline_company_id){
            $query->whereIn('id', function($query) use ($airline_company_id){
                $query->select('flight_id')
                    ->from((new FlightItemModel())->getTable())
                    ->where('airline_company_id', $airline_company_id);
            });
        }

        if($flight_number) {
            $query->where('flight_number', 'like', '%' . $flight_number . '%');
//            $query->whereIn('id', function($query) use ($flight_number){
//                $query->select('flight_id')
//                    ->from((new FlightItemModel())->getTable())
//                    ->whereIn('airline_flight_id', function($query) use ($flight_number){
//                        $query->select('id')
//                            ->from((new BaseFlightModel())->getTable())
//                            ->where('flight_number', $flight_number);
//                    });
//            });
        }

        if($take_off_time_start && $take_off_time_end){
            $query = $query->whereBetween('take_off_time', [$take_off_time_start, $take_off_time_end]);
        }

        if($status){
            $query = $query->where('status', $status);
        }

        $total = $query->count('id');
        $items = $query->with([
                'create_admin',
                'bans' => function($query) {
                    $query->with('ban');
                },
                'orders',
                'items' => function($query) {
                    $query->with('route');
                }
            ])
            ->withCount('take_orders')
            ->withCount('orders')
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $flight_no = [];
            $routes = [];

            foreach($item->items as $flight_line) {
                $flight_number = $flight_line->air_line->flight_number ?? '';
                $date = $flight_line->date ?? '';

                if($date){
                    $d = new \DateTime($date);
                    $date = $d->format('d.M');
                }

                $flight_no[] = $flight_number . '/' . $date;
                $routes[] = $flight_line->route->code ?? '';
//                $transfer_port[] = $flight_line->route->arrive_port_code ?? '';
            }


            $ban_nums = 0;
            $ban_info = [];
            foreach($item->bans as $ban) {
                $ban_nums += $ban->nums;
                $ban_info[] = $ban->ban->name ?? '' . '*' . $ban->nums;
            }


            return [
                'id' => $item->id,
                'status' => $item->status,
                'flight_no' => implode(',', $flight_no),
                'routes' => implode(',', $routes),
                'main_sn' =>  $item->main_sn,
                'take_off_time' => $item->take_off_time,
                'landing_time' => $item->landing_time,
                'lines' => $item->items,
                'bans' => $item->bans,
                'ban_info' => $ban_info,
                'volume' => $item->volume,
                'weight' => $item->weight,
                'take_order_count' => $item->take_orders_count,
                'order_count' => $item->orders_count,
                'big_pkg_count' => $item->orders->sum('big_pkgs'),
                'ban_nums' => $ban_nums,
                'unload_warehouse_id' => $item->unload_warehouse_id,
                'unload_warehouse' => $item->unload_warehouse->name ?? '',
                'cost_amount' => '',
                'carrier' => $item->carrier,
                'cust_type' => $item->cust_type,
                'jh_type' => $item->jh_type,
                'pivot' => $item->pivot,
                'send_email' => $item->send_email,
            ];
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {
            //基础信息
            $flight = new FlightModel();
            $flight->take_off_time = $params['take_off_time'];
            $flight->landing_time = $params['landing_time'];
            $flight->unload_warehouse_id = $params['unload_warehouse_id'];
            $flight->volume = $params['volume'] ?? 0;
            $flight->surplus_volume = $params['volume'] ?? 0;
            $flight->weight = $params['weight'] ?? 0;
            $flight->surplus_weight = $params['weight'] ?? 0;

            $flight_start = \App\Models\airline\base\FlightModel::where('id', $params['lines'][0]['airline_flight_id'])->first();

            if(!$flight_start){
                return $this->error('请选择航班');
            }

            $air_company = CompanyModel::where('id', $params['lines'][0]['airline_company_id'])->first();

            if(!$air_company){
                return $this->error('请选择航空公司');
            }

            $flight->air_company = $air_company->short_name;
            $flight->flight_number = $flight_start->flight_number;
            $flight->flight_date = date('Y-m-d', strtotime($params['take_off_time']));

            $route_start = RouteModel::where ('id', $params['lines'][0]['route_id'])->first();
            if(count($params['lines']) > 1){
                $route_end = RouteModel::where ('id', $params['lines'][count($params['lines']) -1]['route_id'])->first();
                $flight->transfer_port_code = $route_start->arrive_port_code;
            }else{
                $route_end = $route_start;
            }

            $flight->start_port_code = $route_start->start_port_code;
            $flight->start_port_name = $route_start->start_port_name;
            $flight->start_port_country_name = $route_start->start_port_country_name;
            $flight->start_port_country_id = $route_start->start_port_country_id;

            $flight->arrive_port_code = $route_end->arrive_port_code;
            $flight->arrive_port_name = $route_end->arrive_port_name;
            $flight->arrive_port_country_name = $route_end->arrive_port_country_name;
            $flight->arrive_port_country_id = $route_end->arrive_port_country_id;

            $flight->carrier = $params['carrier'];
            $flight->cust_type = $params['cust_type'] ?? 0;
            $flight->jh_type = $params['jh_type'] ?? 0;
            $flight->pivot = $params['pivot'] ?? 0;
            $flight->created_admin_id = $auth->id;
            $flight->save();

            //版型
            foreach($params['bans'] as $ban) {
                FlightBanModel::create([
                    'flight_id' => $flight->id,
                    'ban_id' => $ban['ban_id'],
                    'nums' => $ban['nums']
                ]);
            }

            //航班
            foreach($params['lines'] as $line) {
//                $company = CompanyModel::find($line['airline_company_id']);
//                if(!$company) {
//                    throw new AppException('航空公司错误');
//                }

//                $route_info = RouteModel::where ('id', $line['route_id'])->first();

                FlightItemModel::create([
                    'flight_id' => $flight->id,
                    'route_id' => $line['route_id'],
//                    'start_port_id' => $route_info ->start_port_id,
//                    'destination_id' => $route_info ->destination_id,
//                    'arrive_port_id' => $route_info->arrive_port_id,
                    'airline_company_id' => $line['airline_company_id'],
                    'airline_flight_id' => $line['airline_flight_id'],
                    'date' => $line['date'] ?? '',
                ]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $flight = FlightModel::find($id);
        if(!$flight){
            return $this->error('航班运力不存在');
        }

        DB::beginTransaction();
        try {
            //基础信息
            $flight->take_off_time = $params['take_off_time'];
            $flight->landing_time = $params['landing_time'];
            $flight->unload_warehouse_id = $params['unload_warehouse_id'];
            $flight->volume = $params['volume'];
            $flight->surplus_volume = $params['volume'];
            $flight->weight = $params['weight'];
            $flight->surplus_weight = $params['weight'];

            $flight_start = \App\Models\airline\base\FlightModel::where('id', $params['lines'][0]['airline_flight_id'])->first();

            if(!$flight_start){
                return $this->error('请选择航班');
            }

            $air_company = CompanyModel::where('id', $params['lines'][0]['airline_company_id'])->first();

            if(!$air_company){
                return $this->error('请选择航空公司');
            }

            $flight->air_company = $air_company->short_name;
            $flight->flight_number = $flight_start->flight_number;

            $route_start = RouteModel::where ('id', $params['lines'][0]['route_id'])->first();
            if(count($params['lines']) > 1){
                $route_end = RouteModel::where ('id', $params['lines'][count($params['lines']) -1]['route_id'])->first();
                $flight->transfer_port_code = $route_start->arrive_port_code;
            }else{
                $route_end = $route_start;
            }

            $flight->start_port_code = $route_start->start_port_code;
            $flight->start_port_name = $route_start->start_port_name;
            $flight->start_port_country_name = $route_start->start_port_country_name;
            $flight->start_port_country_id = $route_start->start_port_country_id;

            $flight->arrive_port_code = $route_end->arrive_port_code;
            $flight->arrive_port_name = $route_end->arrive_port_name;
            $flight->arrive_port_country_name = $route_end->arrive_port_country_name;
            $flight->arrive_port_country_id = $route_end->arrive_port_country_id;

            $flight->carrier = $params['carrier'];
            $flight->cust_type = $params['cust_type'] ?? 0;
            $flight->jh_type = $params['jh_type'] ?? 0;
            $flight->pivot = $params['pivot'] ?? 0;
            $flight->save();

            //版型
            FlightBanModel::where('flight_id', $id)->delete();
            foreach($params['bans'] as $ban) {
                FlightBanModel::create([
                    'flight_id' => $flight->id,
                    'ban_id' => $ban['ban_id'],
                    'nums' => $ban['nums']
                ]);
            }

            //航班运力信息
            FlightItemModel::where('flight_id', $id)->delete();
            foreach($params['lines'] as $line) {
                FlightItemModel::create([
                    'flight_id' => $flight->id,
                    'route_id' => $line['route_id'],
                    'airline_company_id' => $line['airline_company_id'],
                    'airline_flight_id' => $line['airline_flight_id'],
                    'date' => $line['date'] ?? '',
                ]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    public function delete(int $id){
        $flight = FlightModel::find($id);

//        $order = OrderModel::where('flight_id', $id)->get();
//        if($order) {
//            return $this->error('该航班运力存在订单，无法删除');
//        }
//
//        $take_order = TakeOrderModel::where('flight_id', $id)->first();
//        if($take_order) {
//            return $this->error('该航班运力存在提单，无法删除');
//        }

        if($flight) {
            DB::transaction(function () use ($flight) {
                FlightBanModel::where('flight_id', $flight->id)->delete();
                FlightItemModel::where('flight_id', $flight->id)->delete();
                TakeOrderModel::where('flight_id', $flight->id)->delete();
                OrderModel::where('flight_id', $flight->id)->update([
                    'flight_id' => 0,
                    'cargo_status' => OrderModel::CARGO_STATUS_NO
                ]);
                $flight->delete();
            });
        }
        return $this->success();
    }

    //配舱信息
    public function info(int $id) {
        $flight = FlightModel::with([
            'bans' => function($query) {
                $query->with(['ban']);
            }
        ])->find($id);

        if(!$flight) {
            return $this->error('航线运力不存在');
        }

        $des_country = $flight->arrive_port_code;
//        $transfer = []; //中转
//        foreach($flight->items as $line) {
//            $transfer[] = $line->arrive_port->name ?? '';
//        }
//
//        if($transfer) {
//            unset($transfer[count($transfer) - 1]);
//        }

        $bans = [];
        foreach($flight->bans as $ban) {
            $ban_name = $ban->ban->name ?? '';
            $ban_nums = $ban->nums ?? 0;
            $bans[] = $ban_name . '*' . $ban_nums;
        }
        $bans = implode(';', $bans);

        //航班信息
        $lines = [];
        foreach($flight->items as $line) {
            $route = $line->route;
            $lines[] = [
                'name' => $route->code ?? '',
                'des_country' => $route->arrive_port_country_name ?? '',
                'start_port' => $route->start_port_code ?? '',
                'arrive_port' => $route->arrive_port_code ?? '',
                'airline_company' => $line->air_company->name ?? '',
                'airline_flight' => $line->air_line->flight_number ?? '',
                'date' => $line->date ?? '',
            ];
        }

        //提单
        $take_order = TakeOrderModel::withCount('orders')
            ->with([
                'orders' => function($query) {
                    $query->withCount('split_order_addr');
                }, 'customer'
            ])->where('flight_id', $id)->get();
        $take_order_info = [];
        $take_order_info['nums'] = $take_order->count(); //提单数
        $take_order_info['order_nums'] = $take_order->sum('orders_count'); //入仓单数
        $big_pkgs = 0;  //大包数
        $split_count = 0;  //分单数
        $volume = 0; //体积
        $volume_weight = 0; //体积重
        $storage_weight_total = 0;
        $take_order_list = []; //提单列表
        foreach($take_order as $item) {
            $big_pkgs += $item->orders->sum('big_pkgs');
            $split_count += $item->orders->sum('split_order_addr_count');

            $pre_volume = $item->orders->sum('storage_volume');
            $volume += $pre_volume;

            $this_volume_weight = $pre_volume * 167;
            $volume_weight += $this_volume_weight;

            $storage_weight = $item->orders->sum('storage_weight');
            $storage_weight_total += $storage_weight;

            $split_order = OrderReceiveModel::whereIn('order_id', $item->orders->pluck('id'))->pluck('sn');

            $take_order_list[] = [
                'customer_name' => $item->customer->name ?? '',
                'sn' => $item->sn,
                'order_sn' => $item->orders->pluck('sn')->implode(','),
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'big_pkgs' => $item->orders->sum('big_pkgs'),
                'order_count' => $item->orders_count,
                'split_order_count' => $item->orders->sum('split_order_addr_count'),
                'des_country_name' => $item->destination ?? '',
                'pre_volume' => $pre_volume,
                'pre_volume_weight' => $this_volume_weight,
                'storage_weight' => $storage_weight,
                'orders' => $item->orders->map(function($order) {
                    return [
                        'customer' => $order->customer->name ?? '',
                        'sn' => $order->sn,
                        'split_order_addr' => $order->split_order_addr->count(''),
                    ];
                }),
                'id' => $item->id,
                'split_order' => $split_order,
                'is_main' => $item->is_main
            ];
        }
        $take_order_info['big_pkgs'] = $big_pkgs;
        $take_order_info['split_count'] = $split_count;
        $take_order_info['volume'] = round($volume, 2);
        $take_order_info['volume_weight'] = round($volume_weight, 2);
        $take_order_info['storage_weight'] = round($storage_weight_total, 2);
        $take_order_info['list'] = $take_order_list;

        $res = [
            'rcl_weight' => $flight->rcl_weight,
            'unload_warehouse' => $flight->unload_warehouse->name ?? '',
            'take_off_time' => $flight->take_off_time,
            'volume' => $flight->volume,
            'weight' => $flight->weight,
            'des_country' => $des_country,
            'transfer' => '',
            'bans' => $bans,
            'status_name' => FlightModel::STATUS_MAPS[$flight->status] ?? '',
            'lines' => $lines,
            'take_order_info' => $take_order_info,
            'carrier' => $flight->carrier,
            'cust_type' => $flight->cust_type,
            'cust_type_name' => OrderModel::separateDecMethod($flight->cust_type),
            'jh_type' => $flight->jh_type,
            'jh_type_name' => $flight->jh_type == 1 ? '交散' : '装板',
        ];

        return $this->success($res);
    }

    //完成配舱
    public function complete(Request $request , $id) {
        $flight = FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班不存在');
        }

        if($flight->status != FlightModel::STATUS_PROGRESS) {
            $flight->status = FlightModel::STATUS_PROGRESS;
        } else {
            $take_order_id = $request->input('take_order_id');
            $take_order = TakeOrderModel::where('flight_id', $id)->find($take_order_id);
            if(!$take_order) {
                return $this->error('主单号错误');
            }
            TakeOrderModel::where('flight_id', $id)->update(['is_main' => 0]);
            $take_order->is_main = 1;
            $take_order->save();

            $flight->status = FlightModel::STATUS_COMPLETED;
            $flight->main_sn = $take_order->sn;
        }

        $flight->save();

        return $this->success();
    }

    //发送邮件-详情
    public function send_email_detail(Request $request){
        $id = $request->input('id');

        $flight = FlightModel::withCount('take_orders')
            ->withCount('orders')->with([
                'take_orders' => function($query){
                    $query->with('orders');
                }
            ])->find($id);
        if(!$flight) {
            return $this->error('航班不存在');
        }

//        $bans = [];
//        foreach($flight->bans as $ban) {
//            $bans[] = [
//                'id' => $ban->ban_id,
//                'name' => $ban->ban->name ?? '',
//                'nums' => $ban->nums ?? 0,
//                'pivot' => $ban->ban->pivot ?? 0,
//            ];
//        }

//        $lines = [];
//        foreach($flight->items as $line) {
//            $lines[] = [
//                'route_id' => $line->route_id,
//                'route_name' => $line->route->name ?? '',
//                'start_port_id' => $line->start_port_id,
//                'start_port_name' => $line->start_port->name ?? '',
//                'arrive_port_id' => $line->arrive_port_id,
//                'arrive_port_name' => $line->arrive_port->name ?? '',
//                'destination_id' => $line->destination_id,
//                'destination_name' => $line->destination->name ?? '',
//                'airline_company_id' => $line->airline_company_id,
//                'airline_company_id' => $line->air_company->name ?? '',
//                'airline_flight_id' => $line->airline_flight_id,
//                'airline_flight_name' => $line->air_line->flight_number ?? '',
//            ];
//        }

        $info = [
            'take_order' => [
                'take_order_count' => $flight->take_orders_count,
                'order_count' => $flight->orders_count,
                'big_pkgs' => $flight->orders->sum('big_pkgs')
            ]
        ];

        $list = [];
        foreach($flight->take_orders as $take_order) {
            //分单号
            $splits = '';
            foreach($take_order->orders as $order) {
                $splits = $order->split_order_addr->pluck('sn')->implode(',');
            }

            //目的地
            $des_country = [];
            $pkgs = [];
            $car_number = [];

            foreach($take_order->orders as $order) {
                $des_country[] = $order->destination ?? '';

                $packages = DictionaryModel::whereIn('id', explode(',', $order->packages))
                    ->pluck('name')->toArray();
                $pkgs = array_merge($pkgs, $packages);
                if($order->car_number){
                    $car_number[] = $order->car_number;
                }

            }

            $des_country = array_unique($des_country);

            $list[] = [
                'id' => $take_order->id,
                'take_order_sn' => $take_order->sn,
                'splits' => $splits,
                'des_country' => implode(",", $des_country),
                'big_pkgs' => $take_order->orders->sum('big_pkgs'),
                'storage_weight' => $take_order->orders->sum('pre_weight'),
                'delivery_date' => date('Y-m-d'),
                'orders_sn' => $take_order->orders->pluck('sn')->implode(","),
                'pkgs' => $pkgs,
                'car_number' => implode(",", $car_number),
                'orders' => $take_order->orders->map(function($order) {
                    return [
                        'id' => $order->id,
                        'airport_id' => $order->airport_id,
                        'des_country' => $item->airport->country_name ?? '',
                        'storage_weight' => $order->storage_weight,
                        'storage_volume' => $order->storage_volume,
                        'packages' => json_decode($order->packages),
                        'big_pkgs' => $order->big_pkgs,
                        'sn' => $order->sn,
                    ];
                })
            ];
        }

        $info['take_order']['list'] = $list;

        return $this->success($info);
    }

    /**
     * 发送邮件
     *
     * 请求示例:
     * {
     *   "id": 123, // 航班ID
     *   "email_id": 1, // 邮箱ID
     *   "flight": {
     *     "take_off_time": "2024-01-01 10:00:00", // 起飞时间
     *     "delivery_time": "2024-01-01 15:00:00", // 交货时间
     *     "lines": [
     *       {
     *         "destination_name": "美国", // 目的地名称
     *         "airline_flight_name": "CA123" // 航班号
     *       }
     *     ],
     *     "bans": [
     *       {
     *         "name": "板型A", // 板型名称
     *         "pivot": "PIVOT信息" // PIVOT信息
     *       }
     *     ]
     *   },
     *   "take_orders": [
     *     {
     *       "take_order_sn": "TO123456", // 提单号
     *       "splits": "SP001,SP002", // 分单号
     *       "des_country": "美国", // 目的地国家
     *       "big_pkgs": "10", // 件数
     *       "storage_weight": "100.5", // 重量
     *       "volume": "2.5", // 方数
     *       "delivery_date": "2024-01-01", // 交货日期
     *       "car_numer": ["京A12345", "京B67890"], // 车牌号数组
     *       "order_sn": "ORD001,ORD002", // 入仓单号
     *       "is_er": "是", // 是否按电交
     *       "remarks": "备注信息", // 备注
     *       "pkgs": [
     *         {
     *           "name": "纸箱", // 包装名称
     *           "nums": "5" // 包装数量
     *         }
     *       ]
     *     }
     *   ]
     * }
     */
    public function send_email(Request $request){
        $id = $request->input('id');

//        $email_id = intval($request->input('email_id', 0));
//        $email = EmailModel::find($email_id);

        $email_ids = $request->input('email_ids', []);
        $emails = EmailModel::whereIn('id', $email_ids)->get();

        if($emails->isEmpty()) {
            return $this->error('请选择要发送的邮箱');
        }



        $flight = FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班不存在');
        }

        $params = $request->all();

        // 数据清理函数
        $cleanData = function($value) {
            if (is_null($value)) {
                return '';
            }
            if (is_array($value)) {
                return implode("\n", array_map(function($item) {
                    return trim(strip_tags((string)$item));
                }, $value));
            }
            // 清理特殊字符，保留换行符
            return trim(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', (string)$value));
        };

        $des = $flight->arrive_port_code;

        $items = $flight->items;
        $flight_number = $items->map(function($item) {
            return $item->air_line->flight_number;
        });

        $flight_number = $flight_number->implode(',');

        $bans = $flight->bans->map(function($ban) {
            return $ban->nums . 'PMC/' . $ban->ban->name;
        });

        $bans = $bans->implode(',');
        $pivot = $flight->pivot;

        //航班信息
        $flight_data = [
            'des' => $cleanData($des),
            'flight_number' => $cleanData($flight_number),
            'take_off_time' => $cleanData($flight->take_off_time),
            'bans' => $cleanData($bans),
            'pivot' => $cleanData($pivot),
        ];

        $data = [$flight_data];

        //提单信息
        if (isset($params['take_orders']) && is_array($params['take_orders'])) {
            foreach($params['take_orders'] as $take_order) {
                $pkgs_data = [];
                $pkgs = $take_order['pkgs'] ?? [];
                if (is_array($pkgs)) {
                    foreach($pkgs as $pkg) {
                        $name = $cleanData($pkg['name'] ?? '');
                        $nums = $cleanData($pkg['nums'] ?? '');
                        if ($name || $nums) {
                            $pkgs_data[] = trim($name . ' ' . $nums);
                        }
                    }
                }

                $car_number = $take_order['car_number'] ?? '';


//                $pre_weight = OrderModel::where('take_order_id', $take_order['id'])->sum('pre_weight');
//                $pre_weight = $pre_weight ?: 0;

                $order_sn = $take_order['orders_sn'] ?? '';
                if($order_sn){
                    $order_sn = explode(',', $order_sn);
                    $order_sn = implode("\n", $order_sn);
                }

                $data[] = [
                    'sn' => $cleanData($take_order['take_order_sn'] ?? ''),
                    'splits' => $cleanData($take_order['splits'] ?? ''),
                    'des_country' => $cleanData($take_order['des_country'] ?? ''),
                    'big_pkgs' => $cleanData($take_order['big_pkgs'] ?? ''),
                    'storage_weight' => $cleanData($take_order['storage_weight'] ?? ''),
                    'packages' => $cleanData($pkgs_data),
                    'order_sn' => $order_sn,
                    'volume' => $cleanData($take_order['volume'] ?? ''),
                    'is_er' => $cleanData($take_order['is_er'] ?? ''),
                    'delivery_date' => $cleanData($take_order['delivery_date'] ?? ''),
                    'car_number' => $cleanData($car_number),
                    'remarks' => $cleanData($take_order['remarks'] ?? '')
                ];
            }
        }



        try {
            $filePath = storage_path('emails/Flight'. $id .'.xlsx');

            // 确保目录存在
            $directory = dirname($filePath);
            if (!is_dir($directory)) {
                mkdir($directory, 0755, true);
            }

            // 如果文件存在，先删除
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            // 验证数据不为空
            if (empty($data)) {
                throw new \Exception('数据为空，无法生成Excel文件');
            }

            // 生成Excel内容并直接写入文件
            $excelContent = Excel::raw(new EmailExport(collect($data)), \Maatwebsite\Excel\Excel::XLSX);
            file_put_contents($filePath, $excelContent);

            // 验证文件是否成功生成
            if (!file_exists($filePath)) {
                throw new \Exception('Excel文件生成失败，文件不存在');
            }

            if (filesize($filePath) == 0) {
                throw new \Exception('Excel文件生成失败，文件为空');
            }

            foreach ($emails as $email){
                Mail::to($email->email)->send(new FlightMail($filePath));
            }

            $flight->email_ids = json_encode($email_ids);
            $flight->send_email = 1;

            return $this->success();
        } catch (\Exception $e) {
            return $this->error('生成Excel文件失败: ' . $e->getMessage());
        }
    }

    //打印
    public function print(Request $request, $id) {

        $filePath = storage_path('emails/Flight'. $id .'.xlsx'); // 指定文件保存路径
        if(file_exists($filePath)) {
            return response()->download($filePath);
        }

        $flight = FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班不存在');
        }

        $params = $request->all();

        // 数据清理函数
        $cleanData = function($value) {
            if (is_null($value)) {
                return '';
            }
            if (is_array($value)) {
                return implode("\n", array_map(function($item) {
                    return trim(strip_tags((string)$item));
                }, $value));
            }
            // 清理特殊字符，保留换行符
            return trim(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', (string)$value));
        };

        $des = array_column($params['flight']['lines'] ?? [], 'destination_name');
        $flight_number = array_column($params['flight']['lines'] ?? [], 'airline_flight_name');
        $bans = array_column($params['flight']['bans'] ?? [], 'name');
        $pivot = array_column($params['flight']['bans'] ?? [], 'pivot');

        //航班信息
        $flight_data = [
            'des' => $cleanData($des),
            'flight_number' => $cleanData($flight_number),
            'take_off_time' => $cleanData($params['flight']['take_off_time'] ?? ''),
            'bans' => $cleanData($bans),
            'pivot' => $cleanData($pivot),
            'delivery_time' => $cleanData($params['flight']['delivery_time'] ?? '')
        ];

        $data = [$flight_data];

        //提单信息
        if (isset($params['take_orders']) && is_array($params['take_orders'])) {
            foreach($params['take_orders'] as $take_order) {
                $pkgs_data = [];
                $pkgs = $take_order['pkgs'] ?? [];
                if (is_array($pkgs)) {
                    foreach($pkgs as $pkg) {
                        $name = $cleanData($pkg['name'] ?? '');
                        $nums = $cleanData($pkg['nums'] ?? '');
                        if ($name || $nums) {
                            $pkgs_data[] = trim($name . ' ' . $nums);
                        }
                    }
                }

                $car_numer = $take_order['car_numer'] ?? [];
                if (!is_array($car_numer)) {
                    $car_numer = [];
                }

                $data[] = [
                    'sn' => $cleanData($take_order['take_order_sn'] ?? ''),
                    'splits' => $cleanData($take_order['splits'] ?? ''),
                    'des_country' => $cleanData($take_order['des_country'] ?? ''),
                    'big_pkgs' => $cleanData($take_order['big_pkgs'] ?? ''),
                    'storage_weight' => $cleanData($take_order['storage_weight'] ?? ''),
                    'volume' => $cleanData($take_order['volume'] ?? ''),
                    'delivery_date' => $cleanData($take_order['delivery_date'] ?? ''),
                    'car_numer' => $cleanData($car_numer),
                    'packages' => $cleanData($pkgs_data),
                    'order_sn' => $cleanData($take_order['order_sn'] ?? ''),
                    'is_er' => $cleanData($take_order['is_er'] ?? ''),
                    'remarks' => $cleanData($take_order['remarks'] ?? '')
                ];
            }
        }

        try {
            // 确保目录存在
            $directory = dirname($filePath);
            if (!is_dir($directory)) {
                mkdir($directory, 0755, true);
            }

            // 如果文件存在，先删除
            if (file_exists($filePath)) {
                unlink($filePath);
            }

            // 验证数据不为空
            if (empty($data)) {
                throw new \Exception('数据为空，无法生成Excel文件');
            }

            // 生成Excel内容并直接写入文件
            $excelContent = Excel::raw(new EmailExport(collect($data)), \Maatwebsite\Excel\Excel::XLSX);
            file_put_contents($filePath, $excelContent);

            // 验证文件是否成功生成
            if (!file_exists($filePath)) {
                throw new \Exception('Excel文件生成失败，文件不存在');
            }

            if (filesize($filePath) == 0) {
                throw new \Exception('Excel文件生成失败，文件为空');
            }

            return response()->download($filePath);
        } catch (\Exception $e) {
            return $this->error('生成Excel文件失败: ' . $e->getMessage());
        }
    }

    //成本明细
    public function pay_info(Request $request, $id) {
        $items = TakeOrderPayModel::whereIn('take_order_id', function($query) use ($id){
            $query->select('id')->from((new TakeOrderModel())->getTable())->where('flight_id', $id);
        })->get();

        $list = $items->map(function($item) {
            // $name = TakeOrderRecModel::TYPE_MAPS[$item->type] ?? '';
            // if($item->type == TakeOrderRecModel::TYPE_OTHER) {
            //     $subject = SubjectModel::find($item->subject_id);
            //     $name = '补录' . ($subject->name ?? '');
            // }

            $subject = SubjectModel::find($item->subject_id);

            return [
                'id' => $item->id,
                'agent_type' => AgentModel::TYPE_LIST[$item->agent->type ?? ''] ?? '',
                'agent_name' => $item->agent->name ?? '',
                'name' => $subject->name ?? '',
                'currency' => $item->currency,
                'amount' => $item->amount,
                'import_amount' => $item->import_amount,
                'verify_status' => $item->verify_status == 2 ? '已核查' : '未核查',
                'bill_status' => $item->bill_status == 2 ? '已出账' : '未出账',
                'pay_status' => $item->pay_status == 2 ? '已付款' : '未付款',
                'create_user' => $item->create_admin->staff->name ?? '系统生成',
                'created_at' => $item->created_at->toDateTimeString(),
                'pay_time' => $item->pay_time,
                'remark' => $item->remark,
                'sys_amount' => $item->sys_amount,
                'symbol' => $item->symbol,
            ];
        });

        $collect = [];
        $collect2 = [];
        foreach($list as $item) {
            if(isset($collect[$item['symbol']])) {
                $collect[$item['symbol']] += $item['amount'];
            } else {
                $collect[$item['symbol']] = $item['amount'];
            }

            if(isset($collect2[$item['symbol']])) {
                $collect2[$item['symbol']] += $item['import_amount'];
            } else {
                $collect2[$item['symbol']] = $item['import_amount'];
            }
        }

        $result = '';
        foreach ($collect as $symbol => $value) {
            if (!empty($result)) {
                $result .= ", ";
            }
            $result .= $symbol . $value;
        }

        $result2 = '';
        foreach ($collect2 as $symbol => $value) {
            if (!empty($result2)) {
                $result2 .= ", ";
            }
            $result2 .= $symbol . $value;
        }


        return $this->success([
            'list' => $list,
            'total' => $result,
            'total2' => $result2
        ]);

    }

    //录入rcl重量
    public function rcl_weight(Request $request) {
        $rcl_weight = $request->input('rcl_weight', '');
        $id = intval($request->input('id'));
        if(!is_numeric($rcl_weight) || $rcl_weight <= 0) {
            return $this->error('RCL重量必须为正数');
        }

        $flight = FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班不存在');
        }

        $flight->rcl_weight = $request->input('rcl_weight');
        $flight->save();

        return $this->success();

    }

    //版号录入
    public function ban_enter(Request $request) {
        $id = intval($request->input('id'));
        $ban_number = $request->input('ban_number', '');
        $ban_weight = $request->input('ban_weight', 0);
        $ban_files = $request->input('ban_files', '');

        $flight = FlightModel::find($id);
        if(!$flight) {
            return $this->error('航班运力不存在');
        }

        $flight->ban_number = $ban_number;
        $flight->ban_weight = $ban_weight;
        $flight->ban_files = $ban_files;
        $flight->save();
        return $this->success();
    }



}
